<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <van-search
      v-model="searchText"
      placeholder="请输入搜索关键词"
      @search="onSearch(searchText)"
      @cancel="$router.back()"
      @focus="handleFocus"
      @input="currentInputChange"
      show-action
    />

    <!-- 搜索结果 -->
    <searchResult v-if="isResultShow" :searchText="searchText" />

    <!-- 联想建议 -->
    <searchAssociation v-else-if="searchText" :searchText="searchText" @changeResult="onSearch"/>

    <!-- 历史记录 -->
    <searchHistory v-else :searchHistoryList="searchHistoryList"  @deleteHistoryD="deleteHistoryD" @deleteHistory="onSearch"/>

  </div>
</template>
<script>
import { getHistories } from '../../api/user'
import searchAssociation from './component/searchAssociation'
import searchHistory from './component/searchHistory'
import searchResult from './component/searchResult'
import { setItem, getItem } from '@/utils/storage'
import { mapState } from 'vuex'
export default {
  name: 'SearchView',
  data () {
    return {
      searchText: '',
      isResultShow: false, // 搜索结果是否显示
      searchHistoryList: getItem('searchHistory') || []// 搜索历史的数据
    }
  },
  components: {
    searchAssociation,
    searchHistory,
    searchResult
  },
  computed: {
    ...mapState(['user'])
  },
  created () {
    this.getHistoriesApi()
  },
  watch: {
    /* 数据持久化（只要数据变化就去做持久化） */
    searchHistoryList () {
      setItem('searchHistory', this.searchHistoryList)
    }
  },
  methods: {
    // 获取用户历史记录
    async getHistoriesApi () {
      const { data } = await getHistories()
      if (this.user) {
        this.searchHistoryList = data.data.keywords
      }
    },

    // 删除历史记录
    deleteHistoryD (str) {
      if (!str) {
        this.searchHistoryList = []
      } else {
        const index = this.searchHistoryList.indexOf(str)
        this.searchHistoryList.splice(index, 1)
      }
    },
    // 搜索时触发
    onSearch (val) {
      this.searchText = val
      this.isResultShow = true
      // 记录历史记录(最新的要靠前，数据不能重复)
      const index = this.searchHistoryList.indexOf(val)
      if (index !== -1) {
        // 进入就说明重复了（那就将它删了）
        this.searchHistoryList.splice(index, 1)
      }
      this.searchHistoryList.unshift(val)
    },

    // 获取焦点时触发
    handleFocus () {
      this.isResultShow = false
    },

    // 输入框发生变化是触发
    currentInputChange (value) {
      this.$store.commit('setInputDate', value)
    }
  }
}
</script>
<style scoped>
</style>
